package com.zhang.springcloud.feignproxy;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author liqiu
 * created on 2018/10/18 17:52
 **/
@Component
public class FeignProxyInvocationHandler implements InvocationHandler, ApplicationContextAware {

	private ApplicationContext applicationContext;

	private Object target;

	public FeignProxyInvocationHandler(Object target) {
		this.target = target;
	}

	public FeignProxyInvocationHandler() {
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		if (method.getName().equals("toString")) {
			return AopUtils.getTargetClass(proxy).toString();
		}
		if (method.getName().equals("equals")) {
			return method.invoke(AopUtils.getTargetClass(proxy), args);
		}
		if (method.getName().equals("hashCode")) {
			return AopUtils.getTargetClass(proxy).hashCode();
		}
		if (target instanceof  Class) {
			Class beanClass = (Class) target;
			String beanName = beanClass.getName();
			method.invoke(applicationContext.getBean(beanName),args);
		}

		return method.invoke(target,args);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
